<template>
  <div class="basic-profile">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>基础画像分析</h2>
        <p>用户人口统计学特征分析，了解用户群体的基本属性分布</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
        <el-button :icon="Download" @click="exportReport">
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 核心指标概览 -->
    <div class="metrics-overview" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="6" v-for="metric in coreMetrics" :key="metric.key">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon">
                <el-icon :size="28" :color="metric.color">
                  <component :is="metric.icon" />
                </el-icon>
              </div>
              <div class="metric-info">
                <h3>{{ metric.title }}</h3>
                <p class="metric-value">{{ metric.value }}</p>
                <span class="metric-desc">{{ metric.description }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表分析区域 -->
    <div class="charts-section" v-loading="loading">
      <!-- 用户画像雷达图 - 独占一行 -->
      <el-row :gutter="20" style="margin-bottom: 24px;">
        <el-col :span="24">
          <el-card class="radar-chart-card">
            <template #header>
              <div class="card-header">
                <h3>
                  <el-icon style="margin-right: 8px;"><Radar /></el-icon>
                  用户画像雷达图
                </h3>
                <div class="radar-info">
                  <el-tag size="small" type="info">多维度用户特征分析</el-tag>
                  <el-button size="small" @click="toggleRadarData">
                    {{ showRadarPercentage ? '显示数量' : '显示占比' }}
                  </el-button>
                </div>
              </div>
            </template>
            <div class="radar-chart-container">
              <div ref="radarChartRef" style="width: 100%; height: 450px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细图表区域 -->
      <el-row :gutter="20">
        <!-- 年龄分布图表 -->
        <el-col :span="12">
          <el-card class="detail-chart-card">
            <template #header>
              <div class="card-header">
                <h3>
                  <el-icon style="margin-right: 8px;"><User /></el-icon>
                  年龄分布
                </h3>
                <el-button-group size="small">
                  <el-button :type="ageChartType === 'bar' ? 'primary' : ''" @click="ageChartType = 'bar'">柱状图</el-button>
                  <el-button :type="ageChartType === 'pie' ? 'primary' : ''" @click="ageChartType = 'pie'">饼图</el-button>
                </el-button-group>
              </div>
            </template>
            <div class="chart-container">
              <div ref="ageChartRef" style="width: 100%; height: 280px;"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 性别分布图表 -->
        <el-col :span="12">
          <el-card class="detail-chart-card">
            <template #header>
              <div class="card-header">
                <h3>
                  <el-icon style="margin-right: 8px;"><Male /></el-icon>
                  性别分布
                </h3>
              </div>
            </template>
            <div class="chart-container">
              <div ref="genderChartRef" style="width: 100%; height: 280px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 地区分布图表 -->
        <el-col :span="12">
          <el-card class="detail-chart-card">
            <template #header>
              <div class="card-header">
                <h3>
                  <el-icon style="margin-right: 8px;"><Location /></el-icon>
                  地区分布
                </h3>
              </div>
            </template>
            <div class="chart-container">
              <div ref="regionChartRef" style="width: 100%; height: 280px;"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 收入分布图表 -->
        <el-col :span="12">
          <el-card class="detail-chart-card">
            <template #header>
              <div class="card-header">
                <h3>
                  <el-icon style="margin-right: 8px;"><Money /></el-icon>
                  收入分布
                </h3>
              </div>
            </template>
            <div class="chart-container">
              <div ref="incomeChartRef" style="width: 100%; height: 280px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, User, Male, Location, Money, Radar
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getBasicProfileAnalysis } from '@/api/analysis'

// 状态管理
const loading = ref(false)
const ageChartType = ref('bar')
const showRadarPercentage = ref(false)

// 图表引用
const radarChartRef = ref(null)
const ageChartRef = ref(null)
const genderChartRef = ref(null)
const regionChartRef = ref(null)
const incomeChartRef = ref(null)

// 分析数据
const analysisData = ref({
  total_users: 0,
  age_distribution: [],
  gender_distribution: [],
  location_distribution: [],
  income_distribution: [],
  summary: {
    avg_age: 0,
    avg_income: 0
  }
})

// 核心指标（基于API数据计算）
const coreMetrics = computed(() => {
  const maleCount = analysisData.value.gender_distribution.find(item => item.label === '男性')?.value || 0
  const femaleCount = analysisData.value.gender_distribution.find(item => item.label === '女性')?.value || 0
  const totalUsers = analysisData.value.total_users || 0
  const topLocation = analysisData.value.location_distribution.length > 0 
    ? analysisData.value.location_distribution.reduce((prev, current) => (prev.value > current.value) ? prev : current).label
    : '暂无数据'
  
  return [
    {
      key: 'total_users',
      title: '总用户数',
      value: totalUsers.toLocaleString(),
      description: '活跃用户总数',
      icon: 'User',
      color: '#409EFF'
    },
    {
      key: 'avg_age',
      title: '平均年龄',
      value: `${analysisData.value.summary.avg_age}岁`,
      description: '用户平均年龄',
      icon: 'Male',
      color: '#67C23A'
    },
    {
      key: 'gender_ratio',
      title: '性别比例',
      value: femaleCount > 0 ? `${(maleCount/femaleCount).toFixed(1)}:1` : '暂无数据',
      description: '男女用户比例',
      icon: 'Female',
      color: '#E6A23C'
    },
    {
      key: 'top_region',
      title: '主要地区',
      value: topLocation,
      description: '用户最多的地区',
      icon: 'Location',
      color: '#F56C6C'
    }
  ]
})

// 加载基础画像分析数据
const loadAnalysisData = async () => {
  try {
    loading.value = true
    const response = await getBasicProfileAnalysis()

    if (response.success) {
      analysisData.value = response.data
      ElMessage.success('数据加载成功')

      // 数据加载完成后初始化图表
      await nextTick()
      initCharts()
    } else {
      ElMessage.error(response.message || '获取分析数据失败')
    }
  } catch (error) {
    console.error('获取基础画像分析数据失败:', error)
    ElMessage.error('获取分析数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  await loadAnalysisData()
}

// 导出报告
const exportReport = () => {
  ElMessage.info('导出功能开发中...')
}

// 切换雷达图数据显示模式
const toggleRadarData = () => {
  showRadarPercentage.value = !showRadarPercentage.value
  if (radarChartRef.value) {
    const chart = echarts.getInstanceByDom(radarChartRef.value)
    if (chart) {
      updateRadarChart(chart)
    }
  }
}

// 初始化所有图表
const initCharts = () => {
  initRadarChart()
  initAgeChart()
  initGenderChart()
  initRegionChart()
  initIncomeChart()
}

// 初始化雷达图
const initRadarChart = () => {
  if (!radarChartRef.value) return

  const chart = echarts.init(radarChartRef.value)
  updateRadarChart(chart)
}

// 更新雷达图
const updateRadarChart = (chart) => {
  // 构建雷达图的6个核心维度
  const indicators = [
    { name: '年轻用户\n(18-35岁)', max: showRadarPercentage.value ? 50 : 500 },
    { name: '中年用户\n(36-50岁)', max: showRadarPercentage.value ? 50 : 500 },
    { name: '男性用户', max: showRadarPercentage.value ? 60 : 600 },
    { name: '女性用户', max: showRadarPercentage.value ? 60 : 600 },
    { name: '城市用户', max: showRadarPercentage.value ? 40 : 400 },
    { name: '高收入用户\n(>10万)', max: showRadarPercentage.value ? 50 : 500 }
  ]

  // 计算各维度数据
  const radarData = []

  // 年轻用户占比 (18-35岁)
  const youngUsers = analysisData.value.age_distribution
    .filter(item => item.label.includes('18-25') || item.label.includes('26-35'))
    .reduce((sum, item) => sum + (showRadarPercentage.value ? item.percentage : item.value), 0)
  radarData.push(youngUsers)

  // 中年用户占比 (36-50岁)
  const middleAgedUsers = analysisData.value.age_distribution
    .filter(item => item.label.includes('36-45') || item.label.includes('46-55'))
    .reduce((sum, item) => sum + (showRadarPercentage.value ? item.percentage : item.value), 0)
  radarData.push(middleAgedUsers)

  // 男性用户
  const maleData = analysisData.value.gender_distribution.find(item => item.label === '男性')
  radarData.push(maleData ? (showRadarPercentage.value ? maleData.percentage : maleData.value) : 0)

  // 女性用户
  const femaleData = analysisData.value.gender_distribution.find(item => item.label === '女性')
  radarData.push(femaleData ? (showRadarPercentage.value ? femaleData.percentage : femaleData.value) : 0)

  // 城市用户
  const urbanData = analysisData.value.location_distribution.find(item => item.label === '城市')
  radarData.push(urbanData ? (showRadarPercentage.value ? urbanData.percentage : urbanData.value) : 0)

  // 高收入用户
  const highIncomeUsers = analysisData.value.income_distribution
    .filter(item => item.label.includes('中高收入') || item.label.includes('高收入'))
    .reduce((sum, item) => sum + (showRadarPercentage.value ? item.percentage : item.value), 0)
  radarData.push(highIncomeUsers)

  const option = {
    title: {
      text: '用户画像多维度分析',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const value = showRadarPercentage.value ? `${params.value}%` : `${params.value}人`
        return `${params.name}: ${value}`
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      textStyle: { color: '#fff' }
    },
    legend: {
      show: false
    },
    radar: {
      indicator: indicators,
      center: ['50%', '55%'],
      radius: '60%',
      startAngle: 90,
      splitNumber: 4,
      shape: 'polygon',
      name: {
        formatter: '{value}',
        textStyle: {
          fontSize: 10,
          fontWeight: 'bold',
          color: '#333'
        }
      },
      splitArea: {
        areaStyle: {
          color: [
            'rgba(64, 158, 255, 0.1)',
            'rgba(64, 158, 255, 0.05)',
            'rgba(64, 158, 255, 0.02)',
            'rgba(64, 158, 255, 0.01)'
          ]
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(64, 158, 255, 0.3)',
          width: 1
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(64, 158, 255, 0.5)',
          width: 2
        }
      }
    },
    series: [{
      name: '用户分布',
      type: 'radar',
      data: [{
        value: radarData,
        name: '用户分布',
        itemStyle: {
          color: 'rgba(64, 158, 255, 0.8)'
        },
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.3)'
        },
        lineStyle: {
          color: '#409EFF',
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8
      }],
      emphasis: {
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.5)'
        },
        lineStyle: {
          width: 4
        }
      }
    }]
  }

  chart.setOption(option, true)
}

// 初始化年龄分布图表
const initAgeChart = () => {
  if (!ageChartRef.value || analysisData.value.age_distribution.length === 0) return

  const chart = echarts.init(ageChartRef.value)
  updateAgeChart(chart)
}

// 更新年龄分布图表
const updateAgeChart = (chart) => {
  const data = analysisData.value.age_distribution.map(item => ({
    name: item.label,
    value: item.value
  }))

  let option = {}

  if (ageChartType.value === 'bar') {
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: '{b}: {c}人',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'transparent',
        textStyle: { color: '#fff' }
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '20%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.name),
        axisLabel: {
          rotate: 45,
          fontSize: 11,
          color: '#666',
          interval: 0,
          margin: 8
        },
        axisLine: {
          lineStyle: { color: '#e0e0e0' }
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          fontSize: 11,
          color: '#666'
        },
        axisLine: {
          lineStyle: { color: '#e0e0e0' }
        },
        splitLine: {
          lineStyle: { color: '#f0f0f0' }
        }
      },
      series: [{
        data: data.map(item => item.value),
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79bbff' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(64, 158, 255, 0.3)'
          }
        }
      }]
    }
  } else {
    option = {
      tooltip: { trigger: 'item', formatter: '{b}: {c}人 ({d}%)' },
      series: [{
        type: 'pie',
        radius: '65%',
        data: data
      }]
    }
  }

  chart.setOption(option, true)
}

// 初始化性别分布图表
const initGenderChart = () => {
  if (!genderChartRef.value || analysisData.value.gender_distribution.length === 0) return

  const chart = echarts.init(genderChartRef.value)
  const data = analysisData.value.gender_distribution.map(item => ({
    name: item.label,
    value: item.value
  }))

  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c}人 ({d}%)' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data: data
    }]
  }

  chart.setOption(option)
}

// 初始化地区分布图表
const initRegionChart = () => {
  if (!regionChartRef.value || analysisData.value.location_distribution.length === 0) return

  const chart = echarts.init(regionChartRef.value)
  const data = analysisData.value.location_distribution.map(item => ({
    name: item.label,
    value: item.value
  }))

  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c}人 ({d}%)' },
    series: [{
      type: 'pie',
      radius: '65%',
      data: data
    }]
  }

  chart.setOption(option)
}

// 初始化收入分布图表
const initIncomeChart = () => {
  if (!incomeChartRef.value || analysisData.value.income_distribution.length === 0) return

  const chart = echarts.init(incomeChartRef.value)
  const data = analysisData.value.income_distribution.map(item => ({
    name: item.label,
    value: item.value
  }))

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}: {c}人',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      textStyle: { color: '#fff' }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '25%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        rotate: 45,
        fontSize: 10,
        color: '#666',
        interval: 0,
        margin: 10
      },
      axisLine: {
        lineStyle: { color: '#e0e0e0' }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 11,
        color: '#666'
      },
      axisLine: {
        lineStyle: { color: '#e0e0e0' }
      },
      splitLine: {
        lineStyle: { color: '#f0f0f0' }
      }
    },
    series: [{
      data: data.map((item, index) => ({
        value: item.value,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: ['#67C23A', '#409EFF', '#E6A23C', '#F56C6C', '#909399'][index % 5] },
            { offset: 1, color: ['#95d475', '#79bbff', '#ebb563', '#f89898', '#b3b3b3'][index % 5] }
          ])
        }
      })),
      type: 'bar',
      barWidth: '45%',
      itemStyle: {
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(103, 194, 58, 0.3)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 监听年龄图表类型变化
watch(ageChartType, () => {
  if (ageChartRef.value && analysisData.value.age_distribution.length > 0) {
    const chart = echarts.getInstanceByDom(ageChartRef.value)
    if (chart) {
      updateAgeChart(chart)
    }
  }
})

// 监听雷达图数据模式变化
watch(showRadarPercentage, () => {
  if (radarChartRef.value) {
    const chart = echarts.getInstanceByDom(radarChartRef.value)
    if (chart) {
      updateRadarChart(chart)
    }
  }
})

// 生命周期
onMounted(() => {
  loadAnalysisData()
})
</script>

<style scoped>
.basic-profile {
  padding: 0;
  background-color: transparent;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.metrics-overview {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.metric-info h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.metric-value {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.metric-desc {
  font-size: 12px;
  color: #999;
}

/* 雷达图卡片样式 - 与其他卡片保持一致 */
.radar-chart-card {
  background: #fff;
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.radar-chart-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.radar-chart-card .el-card__header {
  background: #fafbfc;
  border-bottom: 1px solid #f0f0f0;
}

.radar-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.radar-chart-container {
  padding: 15px 10px 10px 10px;
  background: #fff;
}

/* 详细图表卡片样式 */
.detail-chart-card {
  background: #fff;
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.detail-chart-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.chart-container {
  padding: 15px 10px 10px 10px;
}
</style>

<style scoped>
.basic-profile {
  padding: 0;
  background-color: transparent;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.metrics-overview {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.metric-info h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.metric-value {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.metric-desc {
  font-size: 12px;
  color: #999;
}

.charts-section .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.charts-section .el-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

/* 雷达图信息控制区域 */
.radar-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 详细图表卡片样式 */
.detail-chart-card {
  background: #fff;
}

.detail-chart-card .el-card__header {
  background: #fafbfc;
  border-bottom: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.card-header .el-button-group {
  border-radius: 6px;
  overflow: hidden;
}

.card-header .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

.chart-container {
  padding: 15px 10px 10px 10px;
  background: #fff;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
  background: #fafafa;
  border-radius: 8px;
  margin: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .radar-chart-container {
    padding: 10px 5px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .card-header h3 {
    font-size: 14px;
  }

  .chart-container {
    padding: 10px 5px;
  }
}
</style>
